#!/sbin/openrc-run
# (c) 2016 Alpine Linux

command="/usr/sbin/lxd"
command_args="${LXD_OPTIONS}"
command_background="true"
pidfile="/var/run/${RC_SVCNAME}.pid"

depend() {
	need net
	use lxcfs
	after firewall
}

systemd_ctr() {
	local cmd="$1"
	# Required for lxd to run some systemd containers
	local cgroup=/sys/fs/cgroup/systemd
	local mnt_opts='rw,nosuid,nodev,noexec,relatime,none,name=systemd'

	case "$cmd" in
		mount)
			checkpath -d $cgroup
			if ! mount | grep $cgroup >/dev/null; then
				mount -t cgroup -o $mnt_opts cgroup $cgroup
			fi
			;;
		unmount)
			if mount | grep $cgroup >/dev/null; then
				umount $cgroup
			fi
			;;
	esac
}


start_pre() {
	if yesno "$systemd_container"; then
		systemd_ctr mount
	fi
}

stop() {
	if [ -e /var/lib/lxd/unix.socket ]; then
		$command shutdown
	fi
}

stop_post() {
	systemd_ctr unmount
}
